<?php

namespace App\Admin\Controllers;

use App\Admin\Components\Building2 as Building2Component;
use App\Admin\Components\HouseNewDevices2;
use App\Admin\Components\HouseSessions;
use App\Admin\Components\HouseTickets;
use App\Admin\Components\HouseTotalUsers;
use App\Admin\Components\HouseTotalUsers2;
use App\Admin\Repositories\Room;
use App\Models\Building;
use App\Models\HouseFeeConfig;
use App\Models\Meter;
use App\Services\MeterService;
use Dcat\Admin\Form;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Controllers\AdminController;
use Dcat\Admin\Layout\Row;
use Dcat\Admin\Widgets\Alert;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Admin\Components\Room as RoomComponent;
use App\Admin\Components\Building as BuildingComponent;

class RoomController extends AdminController
{
    public function index(Content $content)
    {
        $building = Building::query()->with('rooms')->find(request()->input('building_id'));
        return $content
            ->title($building->name)
            ->description('房间列表')
            ->body(function (Row $row) use ($building) {
                $row->column(4, new HouseNewDevices2());
                $row->column(8, new BuildingComponent());
            })->body(function (Row $row) use ($building) {
                foreach ($building->rooms as $room) {
                    $row->column(4, new RoomComponent($room));
                }
            });
    }

    public function edit($id, Content $content)
    {
        return $content
            ->title($this->title())
            ->description($this->description()['edit'] ?? trans('admin.edit'))
            ->body($this->form(request()->input('building_id', 0))->edit($id));
    }

    public function create(Content $content)
    {
        $info = '<i class="fa fa-exclamation-circle"></i> 如果该房间不计算水电收费，那么可以无视电表初始值和水表初始值。';
        return $content
            ->title($this->title())
            ->description($this->description()['create'] ?? trans('admin.create'))
            ->body(Alert::make($info)->info())
            ->body($this->form(request()->input('building_id', 0)));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($building_id = 0)
    {
        return Form::make(new Room(), function (Form $form) use ($building_id) {
            $form->display('id');
            $form->text('name')->required();
            $form->textarea('description')->required();
            $form->hidden('building_id')->value($building_id);
            $form->decimal('electric_meter')->default(0)->help('单位：度。 精确到小数点后两位');
            $form->decimal('water_meter')->default(0)->help('单位：吨。 精确到小数点后两位');
            $form->display('created_at');
            $form->display('updated_at');
            $form->disableListButton();

            $form->saving(function (Form $form) {
                // 存入缓存中
                $key = "meter" . $form->input('name');
                $value = [
                    'electric_meter' => $form->input('electric_meter'),
                    'water_meter' => $form->input('water_meter'),
                ];
                Cache::put($key, $value, 20);
                $form->deleteInput(['electric_meter', 'water_meter']);
            });

            $form->saved(function (Form $form, $res) {
                if ($form->isCreating()) {
                    $buildingModel = $form->model()->building();  // 获取建筑模型
                    $buildingModel->is_rent = true;  // 设置为不可出租
                    $buildingModel->save();

                    $houseModel = $buildingModel->house(); // 获取房产模型
                    $houseModel->is_rent = true;  // 设置为不可出租
                    $houseModel->save();

                    $roomModel = \App\Models\Room::query()->find($res);
                    $value = Cache::get("meter" . $roomModel->name);
                    // 插入基础电，水表数据
                    (new MeterService())->initMeter($roomModel, $value['water_meter'], $value['electric_meter']);
                }
                return $form->redirect(route('admin.house.index'));
            });
        });
    }

    public function roomApi(Request $request)
    {
        $buildingId = $request->get('q');
        return \App\Models\Room::query()->where('is_rent', false)->where('building_id', $buildingId)->get(['id', DB::raw('name as text')]);
    }
}
